package 代码题.多线程并发工具类的题目;

import java.util.HashMap;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 测试并发工具类Exchanger,是不是只有两个线程能够交换数据，多个线程是否也能交换数据
 *
 * Exchanger只能两两线程配对交换，局限性太大
 */
public class TestExchanger {

    static final Exchanger<String> exchanger=new Exchanger<>();
    static final ExecutorService threadPool= Executors.newFixedThreadPool(4);

    public static void main(String[] args) {
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                String a="这是a线程";
                try {
                    String b=exchanger.exchange(a);
                    System.out.println("这里是a线程交换来的值："+b);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                String b="这是b线程";
                try {
                    String a=exchanger.exchange(b);
                    System.out.println("这里是b线程交换来的值："+a);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                String c="这是c线程";
                try {
                    String d=exchanger.exchange(c);
                    System.out.println("这里是c线程交换来的值："+d);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                String d="这是d线程";
                try {
                    String c=exchanger.exchange(d);
                    System.out.println("这里是d线程交换来的值："+c);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        threadPool.shutdown();
    }

}
